package com.tinem.platform.service.task.consumer.redis;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.tinem.platform.module.pojo.co.GatewayHeadName;
import com.tinem.platform.module.pojo.co.RedisKeyEnum;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import redis.clients.jedis.exceptions.JedisException;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.concurrent.TimeUnit;

@Slf4j
@Data
@Component
@Configurable
@ConfigurationProperties(prefix = "gateway.req.save.elasticsearch")
public class GatewayReqSaveToElasticsearch implements ApplicationRunner {

    private int threadNum;
    private String elasticsearchUrl;

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        for (int i = 0; i < threadNum; i++) {
            Thread thread = new Thread(()->{
                while (true){
                    try {
                        String gatewayRequestId = stringRedisTemplate.opsForList().leftPop(RedisKeyEnum.gateway_req_info_query.getKey(),1, TimeUnit.DAYS);
                        if(StrUtil.isBlank(gatewayRequestId)){
                            continue;
                        }
                        String redisGatewayRequestId = RedisKeyEnum.gateway_req_info.getKey(gatewayRequestId);
                        Map<Object, Object> req = stringRedisTemplate.opsForHash().entries(redisGatewayRequestId);
                        if(CollUtil.isEmpty(req)){
                            continue;
                        }
                        String s = HttpUtil.post(StrUtil.format(elasticsearchUrl,new HashMap(){{
                            String millis = (String) req.getOrDefault(GatewayHeadName.X_PLATFORM_GATEWAY_CONTEXT_ACCEPT_TIMESTAMP,System.currentTimeMillis()+"");
                            put("date", DateUtil.formatDate(new Date(Long.parseLong(millis))));
                            put("env", req.get(GatewayHeadName.X_PLATFORM_GATEWAY_CONTEXT_ENV));
                            put(GatewayHeadName.X_PLATFORM_GATEWAY_REQUEST_ID, req.get(GatewayHeadName.X_PLATFORM_GATEWAY_REQUEST_ID));
                        }}),JSONObject.toJSONString(req));
                        stringRedisTemplate.delete(redisGatewayRequestId);
                        log.debug(s);
                    }catch (InvalidDataAccessApiUsageException e){
                        if(e.getCause() instanceof JedisException && e.getCause().getCause() instanceof NoSuchElementException){
                            //如果redis中没有数据，则睡眠60秒
                            try {
                                Thread.sleep(60*1000);
                            } catch (InterruptedException ex) {
                                ex.printStackTrace();
                            }
                        }else{
                            log.error("",e);
                        }
                    }catch (Exception e){
                        log.error("",e);
                    }

                }
            });
            thread.setName("gatewayReqSaveElasticsearch-"+i);
            thread.start();
        }

    }
}
